#!/usr/bin/python
# -*- coding: utf-8 -*-
#encoding=utf-8
#author=daimin
'''
Created on 2012-8-22

@author: daimin
数据库处理模块，使用redis做数据存储和缓存
'''
import conf
import redis
import comm


class Conn:
    pass

    
    
    
    
class DbUtil():
    """具体数据库业务处理基类
    """
    __pool     = None
    
    def __init__(self, **kwargs):
        self.__modcfg = kwargs['cfg'] if 'cfg' in kwargs else None
        if DbUtil.__pool is None:
            DbUtil.__pool = redis.ConnectionPool(host=conf.G_CFG['redis']['host'], port=int(conf.G_CFG['redis']['port']))
        self.__dbconn = redis.Redis(connection_pool=DbUtil.__pool, db=conf.G_CFG['redis']['dbname'])
        self.__dbconn.ping()
        ## 流水线
        self._pipe = self.__dbconn.pipeline()
        
        self._tabname = ''
        
    def __append_tabname(self, name, ckey=None):
        """用更多的信息连接表名
        """
        if name is None : return
        ckey = self._tabname if ckey is None else ckey
        self.__tabname = "%s:%s" % (ckey, name)
        return self.__tabname
       
    def _get(self, key):
        return self.__dbconn.get(key)
        
    def _set(self, key, val, expire=0):
        self.__dbconn.set(key, val, expire)
        
    def _getall(self, key):
        return self.__dbconn.keys("%s*")
    
    def _count(self, vals):
        return 0
    
    def _hexist(self, name, key):
        self.__append_tabname(name)
        return self.__dbconn.hexists(self.__hashkey(key), key)
    
    def _hset(self, name, key, val):
        self.__append_tabname(name)
        return self.__dbconn.hset(self.__hashkey(key), key, comm.serialize(val))
    
    def _hget(self, name, key):
        self.__append_tabname(name)
        try:
            return comm.unserialize(self.__dbconn.hget(self.__hashkey(key), key)) 
        except:
            return None
        
    def _del(self, keys):
        if isinstance(keys, list):
            keys = tuple(keys)
        return self.__dbconn.delete(keys)
    
    def __hashkey(self, key):
        return "%s:%s" %(self.__tabname, key[0:6])
    
    def _sadd(self, name, key ,val):
        self.__append_tabname(key, self.__append_tabname(name))
        return self.__dbconn.sadd(self.__tabname, val)
    
    def _smember(self, name, key):
        self.__append_tabname(key, self.__append_tabname(name))
        return self.__dbconn.smembers(self.__tabname)

    def _save(self):
        '''持久化
        '''
        self.__dbconn.bgsave()

    
